package com.acme.domain;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

import com.acme.domain.response.OrderChangeInfo;
import com.acme.domain.response.SubscribeMarketDataResponse;

public class Reader implements Runnable{

	private Socket requestSocket;
	
	Reader(String server,int port,String username) throws IOException{
		requestSocket = new Socket(server,port);
		Thread daemonReader = new Thread(this);
		daemonReader.setDaemon(true);
		daemonReader.start();
		OutputStream out = requestSocket.getOutputStream();
		BufferedOutputStream bos = new BufferedOutputStream(out);
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject("r|"+username);
		oos.flush();
	}
		
	@Override
	public void run() {
		while (true){
			Object resp = readResponse();
			if (resp == null) {
				break;
			} else if ( resp instanceof OrderChangeInfo) {
				Responses.add((OrderChangeInfo) resp);
			} else if ( resp instanceof SubscribeMarketDataResponse){
				new MarketData( ((SubscribeMarketDataResponse)resp).getOrders() );
			}
		}
		
	}
	
	private Object readResponse(){
		
		InputStream in;
		try {
			in = requestSocket.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(in);
			ObjectInputStream ois = new ObjectInputStream(bis);
			return ois.readObject();
		} catch (SocketException e){
		} catch (IOException | ClassNotFoundException e){
			e.printStackTrace();
		}
		return null;
	}
}
